package com.admin.boot.modules.system.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.admin.boot.common.utils.PasswordUtil;
import com.admin.boot.common.utils.RedisUtil;
import com.admin.boot.common.utils.Result;
import com.admin.boot.modules.system.entity.SysUser;
import com.admin.boot.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @version v3.0
 * @Description: TODO
 * @author: jeecg-boot
 * @date: 2024-01-12
 */
@RestController
@RequestMapping("/sys/sysUser")
public class SysUserController {

    @Autowired
    private ISysUserService userService;


    @SaIgnore
    @PostMapping("/login")
    public Result<?> login(@RequestBody SysUser sysUser){
        SysUser user = userService.getByUsername(sysUser.getUsername());
        if (user == null){
            return Result.error("用户名或密码错误！");
        }
        String decrypt = PasswordUtil.decrypt(user.getPassword());
        String password = sysUser.getPassword();
        if (!decrypt.equals(password)){
            return Result.error("用户名或密码错误！");
        }
        StpUtil.login(user.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        StpUtil.getSession().set("user",user);

        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo",user);
        map.put("tokenInfo",tokenInfo);
        return Result.OK(map);
    }


    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(){
        SysUser user = (SysUser) StpUtil.getSession().get("user");
        return Result.OK(user);
    }


    @GetMapping("/logout")
    public Result<?> logout(){
        String id = StpUtil.getLoginIdAsString();
        StpUtil.getSession().delete("user");
        StpUtil.logout();
        return Result.OK("退出成功！");
    }
}

